<?php

class ColorGradient
{
    //0=>Red, 1=>Green, 2=>Blue
    private $arr_start_color_ = array();
    private $arr_end_color_ = array();
    private $arr_calc_colors_;
    private $arr_color_steps_;
    private $iteration_cnt_ = 0;
    private $max_iteration_ = 0;
    
    public function __construct($class_start_color, $class_end_color, $iterations)
    {
        $this->createColorArrays($class_start_color, $class_end_color);
        $this->max_iteration_ = $iterations;
        $this->calculateColors();
    }

    public function __destruct() {}
    
    public function getColor($position)
    {
        if($position < 0 || $position > $this->max_iteration_)
            return false;
        return $this->arr_calc_colors_[$position];
    }
    
    private function calculateColors()
    {
        foreach($this->arr_start_color_  as $key => $value)
            $this->arr_color_steps_[$key] = ($value-$this->arr_end_color_[$key])/$this->max_iteration_;
        for($cnt=0; $cnt<$this->max_iteration_-1; ++$cnt)
        {
            $this->arr_calc_colors_[$cnt][0] = round($this->arr_start_color_[0]-$cnt*$this->arr_color_steps_[0], 0);
            $this->arr_calc_colors_[$cnt][1] = round($this->arr_start_color_[1]-$cnt*$this->arr_color_steps_[1], 0);
            $this->arr_calc_colors_[$cnt][2] = round($this->arr_start_color_[2]-$cnt*$this->arr_color_steps_[2], 0);
        }
        if(($this->max_iteration_-1) > 0)
        {
            $this->arr_calc_colors_[$this->max_iteration_-1][0] = $this->arr_end_color_[0];
            $this->arr_calc_colors_[$this->max_iteration_-1][1] = $this->arr_end_color_[1];
            $this->arr_calc_colors_[$this->max_iteration_-1][2] = $this->arr_end_color_[2];
        }
    }
    
    private function createColorArrays($class_start_color, $class_end_color)
    {
        $this->arr_start_color_[0] = hexdec(substr($class_start_color, 0, 2));
        $this->arr_start_color_[1] = hexdec(substr($class_start_color, 2, 2));
        $this->arr_start_color_[2] = hexdec(substr($class_start_color, 4, 2));
        $this->arr_end_color_[0] = hexdec(substr($class_end_color, 0, 2));
        $this->arr_end_color_[1] = hexdec(substr($class_end_color, 2, 2));
        $this->arr_end_color_[2] = hexdec(substr($class_end_color, 4, 2));
    }
}

?>
